import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;

public class eg10_4 {
    public static void main(String[] args) {
        File helloFile = new File("F://", "Helloworld.txt");
        try {
            // 创建文件
            boolean isCreated = helloFile.createNewFile();
            if (isCreated || helloFile.exists()) {
                String content[] = {
                        "咏柳",
                        "朝代：唐代",
                        "作者：贺知章"
                };
                try (RandomAccessFile fileRandom = new RandomAccessFile(helloFile, "rw")) {
                    for (String str : content) {
                        byte[] contentBytes = str.getBytes("gb2312");
                        fileRandom.write(contentBytes);
                        fileRandom.writeChars(System.getProperty("line.separator"));
                    }
                    String str = "碧玉妆成一树高，万条垂下绿丝条。不知细叶谁裁出，二月春风似剪刀。";
                    long position = fileRandom.length();
                    fileRandom.seek(position);
                    fileRandom.write(str.getBytes("gb2312"));
                    fileRandom.writeChars(System.getProperty("line.separator")); // 添加行结束符
                } // try-with-resources会自动关闭fileRandom

                // 重新打开文件以读取内容
                try (RandomAccessFile fileRandom = new RandomAccessFile(helloFile, "r")) {
                    long position = 0;
                    byte[] buffer = new byte[1024]; // 假设一行不超过1024字节
                    while (position < fileRandom.length()) {
                        fileRandom.seek(position);
                        int bytesRead = fileRandom.read(buffer);
                        if (bytesRead > 0) {
                            String readStr = new String(buffer, 0, bytesRead, "gb2312");
                            System.out.println(readStr);
                        }
                        position += bytesRead;
                    }
                } // try-with-resources会自动关闭fileRandom
            }
        } catch (IOException ex) {
            Logger.getLogger(eg10_4.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}